﻿
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "n2base.h"
#include "fastconv.h"
#include "n2link.h"
#include "ObjScanner.h"

N2StringPool strpool;

static void n2linkAllocTable()
{
    input_objs = new SrcFileTable;
    input_libs = new LibFileTable;
    allsections = new SectionTable;

    Section section;                                       // section 0
    allsections->moveItemInto(&section);

    global_syms = new SymbolTable;
    comdat_syms = new SymbolTable;
    weak_syms = new SymbolTable;
}

static void n2linkFreeTable()
{
    if (weak_syms) {
        delete weak_syms;
        weak_syms = NULL;
    }

    if (comdat_syms) {
        delete comdat_syms;
        comdat_syms = NULL;
    }

    if (global_syms) {
        delete global_syms;
        global_syms = NULL;
    }

    if (input_libs) {
        delete input_libs;
        input_libs = NULL;
    }

    if (input_objs) {
        delete input_objs;
        input_objs = NULL;
    }
}

int n2link()
{
    scanFirstTime();
    return 0;
}

static int main_startup(int argc, char** argv)
{
    // 设置字符串池
    N2PoolString::setStringPool(&strpool);

    // 分配表格
    n2linkAllocTable();

    if (n2linkProcessCommandLine(argc, argv) == 0)
    {
        n2link();
    }

    // 释放表格
    n2linkFreeTable();
    return 0;
}


#ifdef _WIN32
int wmain(int argc, wchar_t** argv)
{
    char ** argvb;
    int i, ret;
    if (n2base_init() < 0)
        return -1;
    argvb = new char *[argc];
    if (argvb == NULL) {
        return -1;
    }

    for (i = 0; i < argc; i++)
    {
        size_t blen;
        char * buff = NULL;
        blen = fcnv_UTF8LengthFromUTF16((WChar_t*)(argv[i]));
        buff = new char[blen + 1];

        fcnv_UTF16ToUTF8(buff, argv[i], 0, NULL);
        argvb[i] = buff;
    }

    ret = main_startup(argc, argvb);

    for (i = 0; i < argc; i++)
        delete[](argvb[i]);
    delete[] argvb;

    return ret;
}

#else

int main(int argc, char** argv)
{
    return main_startup(argc, argv);
}

#endif  //WIN32



